package com.example.springboot.controller;

import com.example.springboot.entity.Student;
import com.example.springboot.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/student")
public class StudentController {

	@Autowired
    private StudentServiceImpl studentService;

	@RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
	public Student getStudentById (@PathVariable(value = "id") Integer id){
		Student student = studentService.getEntityById(id);
		return student;
	}

	
    @RequestMapping("/list")
    public List<Student> getStudents(){

        return studentService.getEntityList();
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
	public Map<String, String> add (@RequestBody Student student){
    	Map<String, String> map = new HashMap<>();
        
		try {
			int orderId = studentService.add(student);
			response(map, orderId);
		} catch (Exception e) {
			error(map);
	        
	        e.printStackTrace();
		}
		
		return map;
	}
    
    
    /**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	public Map<String, String> delete (@PathVariable(value = "id") Integer id){
		Map<String, String> map = new HashMap<>();
		try {
			int ret = studentService.delete(id);
			response(map, ret);
		} catch (Exception e) {
			error(map);
	        
	        e.printStackTrace();
		}
		return map;
	}

 
	/**
	 * 根据id修改信息
	 * @param student
	 * @return
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
	public Map<String, String> update (@PathVariable("id") Integer id, @RequestBody Student student){
		Map<String, String> map = new HashMap<>();
		try {
			int ret = studentService.update(id, student);
			response(map, ret);
		} catch (Exception e) {
			error(map);
	        
			e.printStackTrace();
		}
		return map;
	}


	private void error(Map<String, String> map) {
		map.put("result", "Error");
		map.put("code", "1");
	}



	private void response(Map<String, String> map, int result) {
		if (result <= 0) {
			error(map);
		} else {
			map.put("result", "OK");
		    map.put("code", "0");
		}
	}
}
